package com.xu.cloud.common.wrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 重复读取请求体HttpServletRequestWrapper
 *
 * @author xuguan
 * @since 2023/7/14
 */
@Slf4j
public class XuCloudRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 用来缓存request输入流, 解决只能读取一次的问题
     */
    private final byte[] requestBody;


    public XuCloudRequestWrapper(HttpServletRequest request) {
        super(request);

        // 将request输入流写入字节数组中缓存起来
        try(final ServletInputStream sis = request.getInputStream()) {
            requestBody = StreamUtils.copyToByteArray(sis);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public byte[] getRequestBody() {
        return requestBody;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 将缓存的请求体读到字节输入流
        ByteArrayInputStream bis = new ByteArrayInputStream(requestBody);

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return bis.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bis.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(
                new InputStreamReader(this.getInputStream(), StandardCharsets.UTF_8)
        );
    }
}
